/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package arbitration.gui;

import arbitration.logic.formatter.TextFieldFormatter;
import arbitration.logic.validator.Validator;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

/**
 *
 * @author prophet
 */
public class JTextFieldValidator extends JTextField implements CaretListener, FocusListener {

    private String value;
    private Validator validator;
    private TextFieldFormatter formatter;
    private Color darkGreen = new Color(0, 150, 0);

    public JTextFieldValidator(){
        this(null,null);
    }

    public JTextFieldValidator(Validator validator, TextFieldFormatter formatter) {
        this.validator=validator;
        this.formatter=formatter;
        addCaretListener(this);
        addFocusListener(this);
    }
    
    public String getValue() {
        return value;
    }

    public void setValue(String value) {                
        if (value == null) {
            setText("");
        } else {
            if (validator != null) {
                if (validator.isValid(value) != null) {
                    this.value = value;
                    if(formatter!=null){                        
                        setText(formatter.valueToString(validator.isValid(value)));
                    }else{
                        setText(value);
                    }
                    setForeground(Color.BLACK);
                }
            } else {
                this.value = value;
                setText(value);
                setForeground(Color.BLACK);
            }
        }
    }

    public void caretUpdate(CaretEvent e) {        
        String text = getText();
        if (text.length() == 0) {
            setForeground(Color.BLACK);
            return;
        }

        if (validator != null) {
            if (validator.isValid(text) != null) {
                setForeground(darkGreen);
            } else {
                setForeground(Color.RED);
            }
        } else {
            setForeground(darkGreen);
        }
    }

    public void focusGained(FocusEvent e) {
        if(formatter!=null){
            setText(String.valueOf(formatter.stringToValue(getText())));
        }
    }

    public void focusLost(FocusEvent e) {
        setValue(getText().trim());        
    }

    public TextFieldFormatter getFormatter() {
        return formatter;
    }

    public void setFormatter(TextFieldFormatter formatter) {
        this.formatter = formatter;
    }

    public Validator getValidator() {
        return validator;
    }

    public void setValidator(Validator validator) {
        this.validator = validator;
    }
    
}
